package edu.cmu.cs.webapp.ioms.actions.product;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.FormulaDAOImpl;
import edu.cmu.cs.webapp.ioms.models.FormularRecord;
import edu.cmu.cs.webapp.ioms.models.Product;
import edu.cmu.cs.webapp.ioms.ui.wizards.formula.FormularWizard;
import edu.cmu.cs.webapp.ioms.views.IngredientListView;
import edu.cmu.cs.webapp.ioms.views.ProductView;

public class NewFormulaViewAction implements IViewActionDelegate {
	private IngredientListView _view;
	private Product _product;

	@Override
	public void init(IViewPart view) {
		this._view = (IngredientListView) view;

	}

	@Override
	public void run(IAction action) {
		Object sel = ((IStructuredSelection) ProductView
				.getProductsListViewPart(this._view.getViewSite())
				.getSelection()).getFirstElement();

		if (sel != null && sel instanceof Product) {
			this._product = (Product) sel;
		}

		FormularWizard wizard = new FormularWizard(false, null);
		wizard.setWindowTitle("Add Formula");
		WizardDialog dialog = new WizardDialog(_view.getViewSite().getShell(),
				wizard);
		dialog.setBlockOnOpen(true);
		dialog.open();

		int returnCode = dialog.getReturnCode();

		if (returnCode == org.eclipse.jface.window.Window.OK) {
			FormularRecord formula = wizard.getModel();
			formula.setProduct(_product);

			try{
				
				new FormulaDAOImpl().addFormula(formula);
			} catch (DataAccessException e) {
				e.printStackTrace();
			}

		} else {
		}

		this._view.refIngrListView();
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {

	}

}
